#include "http_respond.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* create  a http resond, must be use destroy_http_resond to free it */
struct http_respond *
create_http_respond(void)
{
    struct http_respond *respond = NULL;
    if ((respond = (struct http_respond *)malloc(sizeof(struct http_respond))) != NULL)
    {
        respond->header = NULL;
        respond->attribute = NULL;
        respond->redirect = NULL;
        respond->data_length = 0;
        respond->data = NULL;
    }
    return (respond);
}

/* */
void
destroy_http_respond(struct http_respond *respond)
{
    if (respond != NULL)
    {
        if (respond->data != NULL)
        {
            free(respond->data);
        }
        if (respond->redirect != NULL)
        {
            free(respond->redirect);
        }
        destroy_key_value(respond->header);
        destroy_key_value(respond->attribute);
        free(respond);
    }
}

void
set_attribute(struct http_respond *respond, char *name, char *value)
{
    if (respond == NULL || name == NULL || value == NULL)
    {
        return ;
    }
    
    struct key_value_pair *new_node = NULL;
    if ((new_node = key_value_pair_malloc()) == NULL)
    {
        return ;
    }
    new_node->key = strdup(name);
    new_node->value = strdup(value);
    
    if (respond->attribute == NULL)
    {
        respond->attribute = new_node;
    } 
    else
    {
        struct key_value_pair *kv = NULL;
        kv = respond->attribute;
        while (kv->next != NULL)
        {
            kv = kv->next;
        }
        kv->next = new_node;
    }
}

void
set_header(struct http_respond *respond, char *name, char *value)
{
    if (respond == NULL || name == NULL || value == NULL)
    {
        return ;
    }
    
    struct key_value_pair *new_node = NULL;
    if ((new_node = key_value_pair_malloc()) == NULL)
    {
        return ;
    }
    new_node->key = strdup(name);
    new_node->value = strdup(value);
    
    if (respond->header == NULL)
    {
        respond->header = new_node;
    } 
    else
    {
        struct key_value_pair *kv = NULL;
        kv = respond->header;
        while (kv->next != NULL)
        {
            kv = kv->next;
        }
        kv->next = new_node;
    }

}

void
set_redirect(struct http_respond *respopnd, const char *path)
{
    if (respopnd != NULL)
    {
        respopnd->redirect = strdup(path);
    }
}

void *
respond_write(struct http_respond *respond, void *data, int size)
{
    if (respond != NULL)
    {
        if ((respond->data = calloc(size + 1, sizeof(char))) == NULL)
        {
            return (NULL);
        }
        memcpy(respond->data, data, size);
        respond->data_length = size;
    }
    return (respond->data);
}
